<template>
  <div class="notice">
    <breadcrumb title="通知管理" homePath="/teacher" />
    <el-card>
      <!-- 发布通知 -->

      <h1>发布通知</h1>
      <el-form
        :model="noticeForm"
        :rules="noticeRules"
        ref="noticeFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <header style="display: flex">
          <el-form-item label="主题" prop="title">
            <el-input
              v-model="noticeForm.title"
              style="width: 200px; margin-right: 20px"
            ></el-input>
          </el-form-item>
          <el-form-item label="* 班级">
            <el-select
              v-model="noticeForm.classes"
              multiple
              placeholder="请选择"
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="item in options"
                :key="item.c_id"
                :label="item.class"
                :value="item.class"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="commitNotice" class="announce"
            >发布</el-button
          >
          <el-button type="primary" @click="toggleContent" class="toggleContent"
            >展开编辑器</el-button
          >
        </header>
        <el-form-item label="* 正文" class="content" v-show="isShow">
          <quill-editor v-model="noticeForm.content" ref="myQuillEditor" />
        </el-form-item>
      </el-form>

      <h1>我发布的通知/管理员通知</h1>
      <!-- 通知 -->
      <el-table :data="allNoticeData" stripe style="width: 100%" border>
        <template slot="empty">
          <p>{{ emptyText }}</p>
        </template>
        <el-table-column prop="n_id" label="序列号" width="100" />
        <el-table-column prop="title" label="主题" />
        <el-table-column label="内容">
          <template slot-scope="scope">
            <div v-html="scope.row.content"></div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <p :class="{ active: values[scope.row.n_id] }">
              {{ scope.row.n_id | filterStatus(readedNoticeList) }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="170">
          <template slot-scope="scope">
            {{ scope.row.create_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              :type="values[scope.row.n_id] ? 'primary' : 'info'"
              round
              @click="toggleReadStatus(scope.row.n_id)"
            >
              {{ values[scope.row.n_id] ? "我还没读" : "完成阅读" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部分页栏 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="allNoticeNum"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import Breadcrumb from "components/Breadcrumb";

import { getUserDataByToken } from "network/users/getUserDataByToken";
import { getCidByCname } from "network/teacher/getCidByCname";

import { announce } from "network/admin/announce";
import { getNotice } from "network/student/getNotice";
import { getNoticeRead } from "network/student/getNoticeRead";
import { goUnRead } from "network/student/goUnRead";
import { goReaded } from "network/student/goReaded";

export default {
  name: "Notice",
  components: {
    Breadcrumb,
  },
  data() {
    return {
      noticeForm: {
        title: "",
        content: "",
        classes: [],
      },
      noticeRules: {
        title: { required: true, message: "请输入通知标题", trigger: "blur" },
      },
      options: [],
      isShow: true,

      allNoticeData: [],
      emptyText: "",
      readedNoticeList: [],
      values: {},
      allNoticeNum: 0,
      queryInfo: {
        currPage: 1,
        pageSize: 2,
      },
      readIdList: [],
    };
  },
  async created() {
    this.$store.commit("setCurrentIndex", {
      type: "teacherCurrentIndex",
      index: 1,
    });
    this.getNotice();
    this.getNoticeRead();
    if (this.allNoticeNum == 0) {
      this.emptyText = "暂无数据";
    }
  },
  async mounted() {
    //获取发布班级
    let user = await getUserDataByToken(window.sessionStorage.getItem("token"));
    let classes = user.classes.split(";");
    let length = classes.length;
    let obj;
    for (let i = 0; i < length; i++) {
      obj = {};
      obj.class = classes[i];
      console.log(classes[i]);
      obj.c_id = await this.getCidByCname(classes[i]);
      console.log(obj.c_id, classes[i]);
      this.options.push(obj);
    }
  },
  filters: {
    filterStatus(n_id, readedNoticeList) {
      let flag = false;
      for (let item of readedNoticeList) {
        // console.log(item);
        if (item.n_id == n_id) {
          flag = true;
          break;
        }
      }
      return flag ? "已读" : "未读";
    },
  },
  methods: {
    // 提交通知
    async commitNotice() {
      const confirmResult = await this.$confirm("确定要发布该通知吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => {
        console.log(err);
      });

      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消了发布");
      }

      let { noticeForm } = this;
      if (noticeForm.classes.length == 0) {
        return this.$message.info("请输入班级");
      }
      if (noticeForm.content == "") {
        return this.$message.info("请输入通知内容");
      }
      this.$refs.noticeFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        noticeForm.classes = noticeForm.classes.join(";");
        console.log(noticeForm);
        await announce(noticeForm);
        this.noticeForm = {
          title: "",
          content: "",
          classes: [],
        };
        this.$message.success("发布通知成功~~~");
        this.queryInfo.pagenum = 1;
        this.queryInfo.pagesize = 2;
        this.getNotice();
      });
    },
    // 切换富文本编辑器
    toggleContent() {
      let input = document.querySelector(".toggleContent");
      let content = document.querySelector(".content");
      if (input.innerText == "收起编辑器") {
        input.innerText = "展开编辑器";
        content.style.height = "0px";
      } else {
        input.innerText = "收起编辑器";
        content.style.height = "360px";
      }
    },
    // 获取所有相关通知
    async getNotice() {
      let token = window.sessionStorage.getItem("token");
      let { currPage, pageSize } = this.queryInfo;
      const res = await getNotice({
        token,
        currPage,
        pageSize,
      });
      this.allNoticeData = res.data;
      this.allNoticeNum = res.total;
      console.log(token, currPage, pageSize);
    },
    // 获取所有已读消息
    async getNoticeRead() {
      let token = window.sessionStorage.getItem("token");
      let res = await getNoticeRead({ token });
      this.readedNoticeList = res;
      // 存储已读Id
      this.values = {};
      res.forEach((item) => {
        this.values[item.n_id] = true;
      });
      // console.log(this.values);
    },
    // 处理改变一页的数量
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getNotice();
    },
    // 处理改变页码
    handleCurrentChange(newPage) {
      this.queryInfo.currPage = newPage;
      this.getNotice();
    },
    // 切换阅读转态
    async toggleReadStatus(n_id) {
      let token = window.sessionStorage.getItem("token");
      let status = this.values[n_id];
      let res;
      if (status) {
        res = await goUnRead({ token, n_id });
      } else {
        res = await goReaded({ token, n_id });
      }
      this.getNotice();
      this.getNoticeRead();
      this.$message.success(res);
    },

    // 获取班级Id
    async getCidByCname(cname) {
      return await getCidByCname(cname);
    },
  },
};
</script>

<style lang="less" scoped>
.notice {
  .el-card {
    h1 {
      text-align: center;
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-bottom: 1px solid #ccc;
    }
    .el-form {
      .content {
        overflow: hidden;
        transition: 0.5s;
        height: 0;
      }
      .toggleContent,
      .announce {
        width: 100px;
        height: 40px;
        position: absolute;
        right: 25px;
      }
      .toggleContent {
        width: 120px;
        right: 130px;
      }
    }
    .el-pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>